<template>
  <div class="addNormalFriend autoGrow flex-row">
    <div class="addOperate layui-form">
      <div class="subTitle">添加类型</div>
      <div class="layui-form-item">
          <select name="city" lay-filter="changeWxType">
            <option value="">请选择添加类型</option>
            <option value="mobile" :selected="wxtype=='mobile'">手机号添加</option>
            <option value="wxid" :selected="wxtype=='wxid'">微信号添加</option>
          </select>
      </div>
      <textarea
        class="inputAccounts"
        :placeholder="wxtype=='mobile' ? '请输入手机号码，每行为一个号码' : '请输入微信号，每行为一个号码'"
        v-model="accounts">
      </textarea>
      <div class="accountsTotal">共计{{formatedAccounts.length}}个号码</div>
      <div class="sendRequests flex-row">
        <button
          @click="sendNow"
          class="layui-btn layui-btn-sm">
          即时发送
        </button>
        <button
          @click="setSendTime"
          class="layui-btn layui-btn-primary layui-btn-sm">
          定时发送
        </button>
      </div>
    </div>
    <add-friend-record
        @cancel="cancelSend"
        :initialRecords="records">
    </add-friend-record>
    <time-picker
      v-if="showDatePicker"
      @closeTimePicker="()=>this.showDatePicker=false"
      @submit="submitSendTime">
    </time-picker>
    <custom-dialog
      v-if="showDialog"
      :closeDialog="closeDialog"
      title="添加好友">
      <div class="wainInfo">
        <p>添加好友数量{{formatedAccounts.length}}</p>
        <p>今日添加好友验证上限：200</p>
      </div>
      <template v-slot:buttons>
        <div class="buttons">
            <button class="layui-btn layui-btn-normal" @click="()=>this.showDialog=false">再次编辑</button>
            <button class="layui-btn layui-btn-normal" @click="forceSend">按上限发送</button>
        </div>
      </template>
    </custom-dialog>
  </div>
</template>
<script>
import {mapState} from 'vuex';
import TimePicker from '@/components/timePicker';
import UserListItem from '@/components/userListItem';
import CustomDialog from '@/components/customDialog';
import AddFriendRecord from '@/components/addFriendRecord';
import {pathOr} from 'ramda'

export default {
  name: 'addNormalFriend',
  data(){
    return {
      wxtype: '',
      accounts: '',
      showDatePicker: false,
      showDialog: false,
      time: '',
      records: [
        // {
        //   csid: 1,
        //   name: '客服一号',
        //   avatar: '',
        //   time: '2019.09.12 11:22',
        //   type: 'instant',
        //   status: 'ongoing',
        //   completeCount: 2,
        //   showDetail: false,
        //   detailType: 'adopt',
        //   targets: [
        //     {
        //       wxid: 'wxid_12466132111',
        //       name: '用户A',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132121',
        //       name: '用户B',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132112',
        //       name: '用户C',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132132',
        //       name: '用户D',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132115',
        //       name: '用户E',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'sent'
        //     },
        //     {
        //       wxid: 'wxid_12463132111',
        //       name: '用户F',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'waiting'
        //     },
        //     {
        //       wxid: 'wxid_12423132111',
        //       name: '用户F',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'failed',
        //       failReason: '对方账号异常，无法添加'
        //     },
        //     {
        //       wxid: 'wxid_22423132111',
        //       name: '用户G',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'failed',
        //       failReason: '没有找到改好友'
        //     }
        //   ]
        // },{
        //   csid: 2,
        //   name: '客服二号',
        //   avatar: '',
        //   time: '2019.09.12 11:22',
        //   type: 'timeing',
        //   status: 'sleeping',
        //   completeCount: 2,
        //   showDetail: false,
        //   detailType: 'adopt',
        //   targets: [
        //     {
        //       wxid: 'wxid_12466132111',
        //       name: '用户A',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132121',
        //       name: '用户B',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132112',
        //       name: '用户C',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132132',
        //       name: '用户D',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132115',
        //       name: '用户E',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'sent'
        //     },
        //     {
        //       wxid: 'wxid_12463132111',
        //       name: '用户F',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'waiting'
        //     },
        //     {
        //       wxid: 'wxid_12423132111',
        //       name: '用户F',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'failed',
        //       failReason: '对方账号异常，无法添加'
        //     },
        //     {
        //       wxid: 'wxid_22423132111',
        //       name: '用户G',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'failed',
        //       failReason: '没有找到改好友'
        //     }
        //   ]
        // },{
        //   csid: 3,
        //   name: '客服三号',
        //   avatar: '',
        //   time: '2019.09.12 11:22',
        //   type: 'instant',
        //   status: 'ongoing',
        //   completeCount: 2,
        //   showDetail: false,
        //   detailType: 'adopt',
        //   targets: [
        //     {
        //       wxid: 'wxid_12466132111',
        //       name: '用户A',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132121',
        //       name: '用户B',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132112',
        //       name: '用户C',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132132',
        //       name: '用户D',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'adopt'
        //     },
        //     {
        //       wxid: 'wxid_12466132115',
        //       name: '用户E',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'sent'
        //     },
        //     {
        //       wxid: 'wxid_12463132111',
        //       name: '用户F',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'waiting'
        //     },
        //     {
        //       wxid: 'wxid_12423132111',
        //       name: '用户F',
        //       gender: 0,
        //       time: '2019.09.12 11:22',
        //       status: 'failed',
        //       failReason: '对方账号异常，无法添加'
        //     },
        //     {
        //       wxid: 'wxid_22423132111',
        //       name: '用户G',
        //       gender: 1,
        //       time: '2019.09.12 11:22',
        //       status: 'failed',
        //       failReason: '没有找到改好友'
        //     }
        //   ]
        // }
      ]
    }
  },
  props: ['params'],
  components: {
    TimePicker,
    UserListItem,
    CustomDialog,
    AddFriendRecord
  },
  mounted() {
    this.$form.on('select(changeWxType)', this.changeWxType)
    this.$form.render();
    const service = pathOr({},['services',0],this.params)
    if(service.csid){
      this.initRecord(service)
    }
  },
  computed: {
    ...mapState(['services']),
    formatedAccounts() {
      if (!this.accounts.trim()) return []
      return this.accounts.split('\n');
    }
  },
  methods: {
    changeWxType({value}){
      this.wxtype = value
    },
    closeDialog() {
      this.showDialog = false
    },
    initRecord(service) {
      this.$api.friend.inviteFriendHistory({
        csId: service.csid,
        wxAccount:service.wxid,
      }).then(data=>{
        this.records = this.transRecords(data)
      }).catch(e=>this.$msg(e))
    },
    transRecords(data){
      return data.map(item=>{
        const service = this.services.filter(s=>s.wxid==item.wxaccountid)[0]
        if(service){
          return {
            ...item,
            name: service.nick,
            avatar: service.avatar,
            time: this.formatTime(item.starttime),
            type: 'instant',
            status: 'ongoing',
            completeCount: item.senditemcount,
            showDetail: false,
            targets: []
          }
        }else{
          return {}
        }
        
      })
    },
    sendNow() {
      if (this.formatedAccounts.length > 200) {
        return this.showDialog = true
      }
      this.send()
    },
    cancelSend(record) {
      this.$api.friend.cancel(record)
        .then(rs=>{
          this.records = this.records.filter(item=>item.id!==record.id)
          this.$msg('操作成功')
        })
    },
    forceSend() {
      this.send(Date.now())
    },
    setSendTime() {
      this.showDatePicker = true
    },
    submitSendTime(time) {
      this.time = time
      this.showDatePicker = false;
      this.send(time)
    },
    addRecord(data){
      const records = this.transRecords([data])
      this.records = [...records,...this.records] 
    },
    async send(time){
      const {services, sleepFrom, sleepTo, minSecond, maxSecond, maxCount, verifyInfo, settingId,verifyCount} = this.params
       
      if (!services || !services[0]) {
        return this.$msg('没有选择客服账号')
      }
      if(maxSecond<minSecond){
        return this.$msg('间隔时间设置错误')
      }
      if(this.wxtype === ''){
        return this.$msg('没有选择添加类型')
      }
      if( verifyCount + this.formatedAccounts.length > maxCount){
        try {
          //超出当日发送上线！超出部分将转入次日发送队列
          const res = await this.$confirm(`<p>添加好友数量：${ this.formatedAccounts.length }</p>
                                          <p>今日添加好友上限：${ Math.max(maxCount-verifyCount,0) }</p>`, '提示', {
            confirmButtonText: '按上限发送',
            cancelButtonText: '再次编辑',
            type: 'warning',
            dangerouslyUseHTMLString: true
          }) 
          if(res === 'cancel'){
            return
          }
        } catch (error) {
          return;
        }
      }
      const type = this.wxtype === 'wxid'?1:0
      const service = services[0]
      let params = {
        csid: service.csid,
        wxaccountid: service.wxid,
        validationmsg: verifyInfo,
        sleepstart: sleepFrom,
        sleepend: sleepTo,
        intervalstart: minSecond,
        intervalend: maxSecond,
        daylimit: maxCount
      }
      try {
        let rs
        rs = await this.$api.friend.updateInviteSetting({
            ...params,
            id: settingId
          })
        const inviteParams = {
          csid: service.csid,
          wxaccountid: service.wxid,
          starttime: time,
          type,
          itemcount: this.formatedAccounts.length,
          friendList: this.formatedAccounts
        }
        try {
          const rs = await this.$api.friend.inviteFriend(inviteParams)   
          this.addRecord(rs) 
          this.$msg('任务创建成功')
        } catch (error) {
          console.log(error)
          this.$msg('任务创建失败')
        }
        
        // todo 查出历史
        
        
      } catch(e) {
        this.$msg(e)
      }
    }
  },
  watch: {
    'params.services': function(val, oldVal) {
      val = val||[]
      oldVal = oldVal||[]
      const newAccount = val[0]||{}
      const oldAccount = oldVal[0]||{}
      if(newAccount.id !== oldAccount.id && newAccount.id){
        const service = val[0]
        this.initRecord(service)
      }
    }
  }
}
</script>
